<?php

namespace App\Http\Controllers;

use App\Models\FolderModel;
use Illuminate\Http\Request;

class FolderController extends Controller
{

    private static function path($path='') : string {
        $path = 'upload' . ($path ? '/'.$path : '');
        return public_path($path);
    }

    public function index(Request $i) {
        $pid    = $i->input('pid', '');
        $dirs   = FolderModel::where('pid', $pid)->get();
        $dirs   = $dirs ?: [];
        return self::success($dirs);
    }

    public function add(Request $i) {
        $pid = $i->input('pid');
        $name = $i->input('name');
        $path = '';
        if ($pid > 0) {
            $parent = FolderModel::find($pid);
            $path = $parent->path . '/' . $parent->name;
        }
        $folder = FolderModel::create([
            'name'  => $name,
            'pid'   => $pid,
            'path'  => $path
        ]);

        return self::success($folder);
    }

    public function update(Request $i) {
        $old    = $i->input('old');
        $new    = $i->input('new');
        $old    = self::path($old);
        $new    = self::path($new);
        rename($old, $new);
        return self::success();
    }

    public function delete(Request $i) {
        $id = $i->input('id');
        // 检查其下是否还有文件
        $folder = FolderModel::find($id);
        $path = $folder->path . '/' . $folder->name;
        FolderModel::where('path', 'like', "{$path}%")->delete();
        $folder->delete();
        return self::success();
    }
}
